package com.mingke.java.task;

import com.mingke.java.params.OperationBaseParams;
import com.mingke.java.utils.DataSourceUtils;

import java.sql.ResultSet;

/**
 * 快速插入的任务
 */
public class FastInsertTask implements Task{

    private String selectSQL;

    private String insertRawSQL;

    private OperationBaseParams params;

    @Override
    public String doTask() {
        DataSourceUtils sourceUtils = new DataSourceUtils();
        sourceUtils.initSimpleConnection(params.getSourceDBURL(), params.getSourceUser(), params.getSourcePassword());
        ResultSet resultSet = sourceUtils.doSQL(selectSQL);

        DataSourceUtils targetUtils = new DataSourceUtils();
        targetUtils.initSimpleConnection(params.getTargetDBURL(), params.getTargetUser(), params.getTargetPassword());

        long realBegin = System.currentTimeMillis();
        long begin = System.currentTimeMillis();
        long end = 1L;

        targetUtils.initBatchExecutor(insertRawSQL);
        try {
            int index = 0;
            int columnNum = resultSet.getMetaData().getColumnCount();
            //遍历数据
            while(resultSet.next()) {
                //填充参数
                Object objs[] = new Object[columnNum];
                //将列值取出直接放到Object数组中
                for (int i = 1; i <= columnNum; i++) {
                    objs[i-1] = resultSet.getObject(i);
                }
                targetUtils.fillBatchSQLParams(objs);

                //执行批量代码
                if(index % DataSourceUtils.fetchSize == 0) {
                    targetUtils.doBatchSQL();
                }
                index++;
            }
            //System.out.println("FetchSize: "+value.getResultSet().getFetchSize());
        } catch (Exception e) {
            e.printStackTrace();
        }
        targetUtils.doBatchSQL();

        //关闭资源
        sourceUtils.close();
        targetUtils.close();
        end = System.currentTimeMillis();
        return "程序执行时间"+(end-realBegin)+"ms";
    }

    public FastInsertTask() {
    }

    public String getSelectSQL() {
        return selectSQL;
    }

    public void setSelectSQL(String selectSQL) {
        this.selectSQL = selectSQL;
    }

    public String getInsertRawSQL() {
        return insertRawSQL;
    }

    public void setInsertRawSQL(String insertRawSQL) {
        this.insertRawSQL = insertRawSQL;
    }

    public OperationBaseParams getParams() {
        return params;
    }

    public void setParams(OperationBaseParams params) {
        this.params = params;
    }

    public FastInsertTask(String selectSQL, String insertRawSQL, OperationBaseParams params) {
        this.selectSQL = selectSQL;
        this.insertRawSQL = insertRawSQL;
        this.params = params;
    }
}
